import APIConfig from "../config/api";
import exceptionMessage from "../config/exception-message";
import cache from "../enum/cache";
import User from "../model/user";
import { wxToPromise } from "./wx";
class Http{ 
  static async request({url,data,method='GET',refetch = true}){

    let res;
    try{
       res = await wxToPromise('request',{
        url:  APIConfig.baseUrl + url, 
        data, method,
        header:{
          token: wx.getStorageSync(cache.title)
        }
       });
    }catch(e){
      Http._showError(-1);
      throw Error(e.errMsg);
    }
      
         // 全局统一的响应 异常处理
        // 请求成功 
        if(res.statusCode < 400 ){
          return res.data.data
        } 
        // 请求失败
        if(res.statusCode === 401){
          // 令牌相关操作 
          if(res.data.error_code === 10001){
              wx.navigateTo({
                url: '/pages/login/login',
              })
              throw Error('请求未携带令牌');
          }

          // 自动刷新令牌
          if(refetch){
            return await Http._refetch({url,data,method,refetch})
          }
         
 
        } 
        // 提示错误信息
        Http._showError(res.data.error_code,res.data.message); 

        // 抛出异常
        const error = Http._generateMessage(res.data.message);
        throw Error(error);
  }

  // 刷新用户登录的操作
  static async _refetch(data){
    await  User.login();
    data.refetch = false;
    return await Http.request(data)
  }

  static _showError(errCode,message){
    // console.log(errCode);
    let title = '';
    const errorMessage = exceptionMessage[errCode]; 
    title = errorMessage || message || "未知异常" 
    title =  Http._generateMessage(title); 
    wx.showToast({
      title,
      icon:'none',
      duration:3000
    })
  }

  static _generateMessage(message){
     return  message = typeof message === 'object' ? Object.values(message).join(';') : message; 
  }

}

export default Http